<?php

namespace Melo\Config;

use Illuminate\Support\Str;

/**
 * Created by PhpStorm.
 * User: tusimo
 * Date: 10/28/19
 * Time: 7:08 PM
 */
class Container
{
    private static $config;

    private function __construct()
    {
        throw new \Exception('not allowed construct');
    }

    /**
     * 调用实例化
     * @param $configServer
     * @param $appId
     * @param $namespaces
     * @param null $savePath
     * @param null $clientIp
     * @return Config
     * @throws \Exception
     */
    public static function register($configServer, $appId, $namespaces, $savePath = null, $clientIp = null, $cluster = 'default')
    {
        self::$config = new Config($configServer, $appId, $namespaces, $savePath, $clientIp, $cluster);
        self::registerOsEnv();
        return self::$config;
    }

    private static function registerOsEnv()
    {
        //register os env
        $osEnvs = getenv();
        if (!empty($osEnvs)) {
            foreach ($osEnvs as $key => $item) {
                if (Str::startsWith($key, 'MELO_')) {
                    $key = str_replace('_', '.', strtolower(ltrim($key, 'MELO_')));
                    if (Str::contains($key, '\.')) {
                        $key = str_replace('\.', '_', $key);
                    }
                    self::$config->set($key, $item);
                }
            }
        }
    }

    public static function instance()
    {
        if (self::$config) {
            return self::$config;
        }
        throw new \Exception("config is not registered, call register before ");
    }

    private function __clone()
    {
        throw new \Exception('not allowed clone');
    }
}
